/**
*	AssetManager
*	@author 	Liam O'Donnell 2008-04-18
**/

package com.spikything.utils {
	
	import com.spikything.utils.AssetLoader;
	import com.spikything.utils.events.AssetLoaderEvent;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.EventDispatcher;

	public class AssetManager {
		
		public var target 			:Sprite;
		private var _assets 		:Array; 	// of AssetLoader objects
		private var _stack 			:Array; 	// of String objects
		//private var _ids 			:Object;
		private var _callback 		:Function;
		private var _callbackParams :Object;
		
		public function AssetManager () {
			_assets = new Array();
			//_ids = new Array();
			_stack = new Array();
		}
		
		public function get assets ():Array { return _assets };
		//public function get ids ():Object { return _ids };
		
		public function getAsset (id:String):MovieClip {
			for (var i:int=0; i<assets.length; i++) if (assets[i].id == id) return assets[i].content;
			return undefined;
		}
		
		public function loadAssets (assetList:Array, target:Sprite, callback:Function = null, callbackParams:Object=null):void {
			for (var i:int=0; i<assetList.length; i++) _stack.push(assetList[i]);
			this.target = target;
			_callback = callback;
			_callbackParams = callbackParams;
			loadNextAsset();
		}
		
		// TODO find asset by id/url method: loader.assetURL
		
		public function loadAsset (url:String, target:Sprite):AssetLoader {
			trace(">> loadAsset(" + url + ", " + target);
			var loader:AssetLoader = new AssetLoader(null, target);
			loader.addEventListener(AssetLoaderEvent.LOADED, loadNextAsset); //, false, 0, true
			loader.addEventListener(AssetLoaderEvent.ERROR, loadError);
			loader.loadAsset(url, target);
			_assets.push(loader);
			//_ids[loader.id.split(".").join("-")] = loader.content;
			return loader;
		}
		
		private function loadNextAsset (e:AssetLoaderEvent = null):void {
			trace("~~~ loadNextAsset();");
			if (!_stack.length) {
				trace(">> AssetLoaderEvent.ALL_DONE : "+_callback);
				if (_callback != null) _callback(_callbackParams);
				target.dispatchEvent(new AssetLoaderEvent(AssetLoaderEvent.ALL_DONE));
				return;
			}
			var loader:AssetLoader = loadAsset(_stack.shift(), target);
			//loader.addEventListener(AssetLoaderEvent.LOADED, loadNextAsset);
			//loader.addEventListener(AssetLoaderEvent.ERROR, loadError);
			//_assets.push(loader);
			//_ids[loader.id.split(".").join("-")] = loader.content;
		}		
		
		private function loadError (e:AssetLoaderEvent):void {
			throw new Error("Error loading content");
		}
	
	}

}